package iPod;

import java.io.*;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

public class IDBChunk {
	// Temporary access variable
	protected byte item[] = new byte[4];
	protected long startPos = 0;
	protected String expectedID = null;
	
	// Chunk data
	protected String typeID = null;
	protected int headerSize = 0;
	protected int recordSize = 0;   
    
    // Derived types overload these
    public void readChild(IDBChunk chunk, RandomAccessFile in) throws Exception
    {
    	System.out.println("Unrecognised Chunk - " + chunk.typeID.toUpperCase());
    }
    
    // chunk access functions
    public void load(RandomAccessFile in) throws Exception
    {
    	// Load header information
    	loadRecord(in);
    	
    	// read the children
    	loadChildren(in);   	    
    }
    
    public void loadRecord(RandomAccessFile in) throws Exception
    {
    	// Mark the beginning of this block (so we can reset)
    	startPos = in.getFilePointer();
    	
    	// read the header
    	loadHeader(in); 
    	
    	// jump back to the beginning
    	in.seek(startPos);
    }
    
    public void loadHeader(RandomAccessFile in) throws Exception
    {      	
    	// Read the typeID
    	in.read(item);
    	typeID = new String(item);
    	if (expectedID != null && !expectedID.equalsIgnoreCase(typeID))
    		throw new Exception("Unexpected typeID read - " + typeID);
    	
    	// read the size of the header
    	in.read(item);
    	headerSize = DataUtils.littleEndianToInt(item);
    	
    	// read the size of this record
    	in.read(item);
    	recordSize = DataUtils.littleEndianToInt(item);
    }
    
    public void loadChildren(RandomAccessFile in) throws Exception
    {
    	in.seek(startPos + headerSize);    	
    	
    	while (in.getFilePointer() < startPos + recordSize)
		{
			// Read all the chunks possible in the file
			IDBChunk chunk = new IDBChunk();
			chunk.loadRecord(in);
			
			// Read the data from the chunk
			readChild(chunk, in);
			
			// Move on to the next chunk
			chunk.skip(in);		
		}
    }   
    
    public void skip(RandomAccessFile in) throws Exception
    {
    	if (typeID.charAt(2) == 'l')
    	{
    		// Record size represents the number of children it has in 
    		// mhlp, mhla, mhlt
    		in.seek(startPos + headerSize);
    		for (int index = 0; index < recordSize; ++index)
    		{
    			IDBChunk chunk = new IDBChunk();
    			chunk.loadRecord(in);
    			chunk.skip(in);    		
    		}
    	}
    	else
    	{
    		in.seek(startPos + recordSize);
    	}
    }
}
